package org.hamster.multidropbox.dropbox.command
{
	import mx.collections.ArrayCollection;
	import mx.events.CollectionEvent;
	
	import org.hamster.common.puremvc.events.ParallelEvent;
	import org.hamster.common.puremvc.events.ParallelEventHandler;
	import org.hamster.dropbox.DropboxEvent;
	import org.hamster.dropbox.models.DropboxFile;
	import org.hamster.multidropbox.dropbox.event.AppDropboxEvent;
	import org.hamster.multidropbox.dropbox.vo.AppDropboxClient;
	import org.hamster.multidropbox.dropbox.vo.AppDropboxFile;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;
	
	public class DropboxGetMetadataListCommand extends SimpleCommand
	{
		private var resultMetadataList:ArrayCollection = new ArrayCollection();
		
		public function DropboxGetMetadataListCommand()
		{
			super();
		}
		
		override public function execute(notification:INotification):void
		{
			resultMetadataList = new ArrayCollection();
			
			var body:Object = notification.getBody();
			var clientList:ArrayCollection = body.clientList;
			var path:String = body.path;
			var parallelHandler:ParallelEventHandler = new ParallelEventHandler();
			parallelHandler.quitWhenFailed = false;
			for each (var client:AppDropboxClient in clientList) {
				parallelHandler.addChild(client, 
					[DropboxEvent.METADATA_RESULT, DropboxEvent.METADATA_RESULT_NOT_MODIFIED], 
					DropboxEvent.METADATA_FAULT);
				
				client.addEventListener(DropboxEvent.METADATA_RESULT, metadataResultHandler);
			}
			
			parallelHandler.addEventListener(ParallelEvent.ALL_FINISHED, allFinishedHandler);
			parallelHandler.addEventListener(ParallelEvent.ALL_FAILURE, allFailureHandler);
			
			
		}
		
		private function metadataResultHandler(event:DropboxEvent):void
		{
			var client:AppDropboxClient = event.currentTarget as AppDropboxClient;
			client.removeEventListener(DropboxEvent.METADATA_RESULT, metadataResultHandler);
			
			var results:Array = (event.resultObject as DropboxFile).contents;
			for each (var dropboxFile:DropboxFile in results) {
				this.resultMetadataList.addItem(new AppDropboxFile(client, dropboxFile));
			}
			
		}
		
		private function allFinishedHandler(event:ParallelEvent):void
		{
			this.sendNotification(AppDropboxEvent.DROPBOX_METADATA_LIST_RESULT, this.resultMetadataList);
		}
		
		private function allFailureHandler(event:ParallelEvent):void
		{
			this.sendNotification(AppDropboxEvent.DROPBOX_METADATA_LIST_FAULT, null);
		}
	}
}